package com.example.print.fragment;


import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.print.R;
import com.example.print.activity.MainActivity;
import com.example.print.utility.CodeUtils;
import com.panling.printapi.Printer;
import com.panling.printapi.StringUtility;


/**
 * A simple {@link Fragment} subclass.
 */
public class PrintCodeFragment extends Fragment {
    protected String TAG = "PrintCodeActivity";

    private RadioButton code_upc, code_ean8, code_ean13, code_code39, code_itf, code_code128, code_qr;
    private TextView previewtext, texthint;
    private Button generatecode, btn_codeprint;
    private EditText et_hint, code_Paper_distance, code_chroma;
    private ImageView img_code;
    private RadioGroup barcodeTypeRadioGroup;

    private int barcodeType = 0;
    private int p_distance = 3 , p_chroma = 25;
    private MainActivity mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_printcode, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mContext = (MainActivity) getActivity();

        //获取对应控件
        code_upc = mContext.findViewById(R.id.code_upc);
        code_ean8 = mContext.findViewById(R.id.code_ean8);
        code_ean13 = mContext.findViewById(R.id.code_ean13);
        code_code39 = mContext.findViewById(R.id.code_code39);
        code_itf = mContext.findViewById(R.id.code_itf);
        code_code128 = mContext.findViewById(R.id.code_code128);
        code_qr = mContext.findViewById(R.id.code_qr);
        previewtext = mContext.findViewById(R.id.previewtext);
        texthint = mContext.findViewById(R.id.texthint);
        et_hint = mContext.findViewById(R.id.et_hint);
        img_code = mContext.findViewById(R.id.img_code);
        generatecode = mContext.findViewById(R.id.generatecode);
        btn_codeprint = mContext.findViewById(R.id.btn_codeprint);
        barcodeTypeRadioGroup = mContext.findViewById(R.id.barcodeTypeRadioGroup);

        //走纸距离及浓度
        code_Paper_distance = mContext.findViewById(R.id.code_Paper_distance);
        code_chroma = mContext.findViewById(R.id.code_chroma);

        code_upc.setOnCheckedChangeListener(onCheckedChangeListener);
        code_ean8.setOnCheckedChangeListener(onCheckedChangeListener);
        code_ean13.setOnCheckedChangeListener(onCheckedChangeListener);
        code_code39.setOnCheckedChangeListener(onCheckedChangeListener);
        code_itf.setOnCheckedChangeListener(onCheckedChangeListener);
        code_code128.setOnCheckedChangeListener(onCheckedChangeListener);
        code_qr.setOnCheckedChangeListener(onCheckedChangeListener);

        //点击生成时候条码显示在条码展示区功能，能生成条码，打印功能暂未实现
        generatecode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String barcodeData = et_hint.getText().toString().trim();  // 获取输入的文字并去除前后空格
                String paper_dis = code_Paper_distance.getText().toString().trim();
                String chroma = code_chroma.getText().toString().trim();
                try {
                    p_distance = Integer.parseInt(paper_dis);
                    p_chroma = Integer.parseInt(chroma);
                } catch (Exception var8) {
                    p_distance = 3;
                    p_chroma = 35;
                }

                byte[] data = barcodeData.getBytes();
                int leng = data.length;
                if (!barcodeData.isEmpty()) {  // 判断文字不为空
                    int checkedRadioButtonId = getCheckedRadioButtonIdInRadioGroup(barcodeTypeRadioGroup);
                    Log.e(TAG, "length: " + leng);
                    if (checkedRadioButtonId == R.id.code_upc) {
                        if (leng != 11) {
                            Toast.makeText(mContext, "输入长度只能为11位数字", Toast.LENGTH_SHORT).show();
                        } else if (!StringUtility.isDecimal(barcodeData)) {
                            Toast.makeText(mContext, "不是有效数据！", Toast.LENGTH_SHORT).show();
                        } else {
                            barcodeType = 0;
                            img_code.setImageBitmap(CodeUtils.createUPCABarcode(barcodeData));
                        }
                    } else if (checkedRadioButtonId == R.id.code_ean8) {
                        // if (isValidEAN8(barcodeData)) {
                        if (leng != 7) {
                            Toast.makeText(mContext, "输入长度只能为7位数字！", Toast.LENGTH_SHORT).show();
                        } else if (!StringUtility.isDecimal(barcodeData)) {
                            Toast.makeText(mContext, "只能输入0~9的数字！", Toast.LENGTH_SHORT).show();
                        } else {
                            img_code.setImageBitmap(CodeUtils.createEAN8Barcode(barcodeData));
                            barcodeType = 1;
                        }

                    } else if (checkedRadioButtonId == R.id.code_ean13) {
                        //if (isValidEAN13(barcodeData)) {
                        if (leng != 12) {
                            Toast.makeText(mContext, "输入长度只能为12位数字！", Toast.LENGTH_SHORT).show();
                        } else if (!StringUtility.isDecimal(barcodeData)) {
                            Toast.makeText(mContext, "只能输入0~9的数字！", Toast.LENGTH_SHORT).show();
                        } else {
                            img_code.setImageBitmap(CodeUtils.createEAN13arcode(barcodeData));
                            barcodeType = 2;
                        }

                    } else if (checkedRadioButtonId == R.id.code_code39) {
                        for (int k = 0; k < data.length; k++) {
                            int d = data[k];
                            if ((d >= 48 && d <= 57) || (d >= 65 && d <= 90)
                                    || d == 32 || d == 36 || d == 37 || (d >= 42 && d <= 47 && d != 44)) {
                                barcodeType = 3;
                                img_code.setImageBitmap(CodeUtils.createCODE39arcode(barcodeData));
                                //可以打印
                            } else {
                                Toast.makeText(mContext, "不是有效数据！", Toast.LENGTH_SHORT).show();
                            }
                        }

                    } else if (checkedRadioButtonId == R.id.code_itf) {
                        if (leng < 2 || leng > 255 || (leng % 2) != 0) {
                            Toast.makeText(mContext, "输入长度只能为小于等于24位数字的偶数", Toast.LENGTH_SHORT).show();
                        } else if (!StringUtility.isDecimal(barcodeData)) {
                            Toast.makeText(mContext, "不是有效数据！", Toast.LENGTH_SHORT).show();
                        } else
                            barcodeType = 4;
                        img_code.setImageBitmap(CodeUtils.createITFarcode(barcodeData));
                    } else if (checkedRadioButtonId == R.id.code_code128) {
                        if (leng < 1 || leng > 255) {
                            Toast.makeText(mContext, "输入长度只能为1~30位字符，不包括汉字", Toast.LENGTH_SHORT).show();
                        }
                        for (int k = 0; k < data.length; k++) {
                            int d = data[k] & 0xFF;
                            if ((d < 0 || d > 127) && (d < 193 || d > 196)) {
                                Toast.makeText(mContext, "不是有效数据！", Toast.LENGTH_SHORT).show();
                            }
                        }
                        barcodeType = 5;
                        img_code.setImageBitmap(CodeUtils.createCODE128Barcode(barcodeData));
                    } else if (checkedRadioButtonId == R.id.code_qr) {
                        barcodeType = 6;
                        img_code.setImageBitmap(CodeUtils.generateBitmap(barcodeData, 320, 320));
                    }
                } else {
                    Toast.makeText(mContext, "请输入数据", Toast.LENGTH_SHORT).show();
                }
                if ((p_distance < 0 || p_distance > 5) && (p_chroma < 0 || p_chroma > 35)) {
                    Toast.makeText(mContext, "走纸设置范围为0-5,浓度范围为0-35", Toast.LENGTH_SHORT).show();
                }
            }
        });

        /**
         * 条码打印监听事件，功能暂时实现
         */
        btn_codeprint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String paper_dis = code_Paper_distance.getText().toString().trim();
                String chroma = code_chroma.getText().toString().trim();
                try {
                    p_distance = Integer.parseInt(paper_dis);
                    p_chroma = Integer.parseInt(chroma);
                } catch (Exception var8) {
                    p_distance = 3;
                    p_chroma = 35;
                }
                try {
                    // mPrinter.print("123456", Printer.BarcodeType.CODE39);
                    String barcodeData = et_hint.getText().toString().trim();  // 获取输入的文字并去除前后空格
                    byte[] data = barcodeData.getBytes();
                    Log.e(TAG, "btn_codeprint :" + barcodeData + " type: " + barcodeType + " dis: " + p_chroma + " ret: " + p_chroma);
                    mContext.mPrinter.initPrint();
                    //设置居中模式
                    mContext.mPrinter.setPrintAlignmentMode(1);
                    //设置打印的浓度
                    mContext.mPrinter.setPrintChromaLevel(p_chroma);
                    switch (barcodeType) {
                        case 0:
                            mContext.mPrinter.printBarcode(barcodeData, Printer.BarcodeType.UPC_A);
                            //打印完走纸设置的行数
                            mContext.mPrinter.setFeedRow(0, p_distance);
                            break;
                        case 1:
                            mContext.mPrinter.printBarcode(barcodeData, Printer.BarcodeType.JAN8_EAN8);
                            //打印完走纸设置的行数
                            mContext.mPrinter.setFeedRow(0, p_distance);
                            break;
                        case 2:
                            mContext.mPrinter.printBarcode(barcodeData, Printer.BarcodeType.JAN13_EAN13);
                            //打印完走纸设置的行数
                            mContext.mPrinter.setFeedRow(0, p_distance);
                            break;
                        case 3:
                            mContext.mPrinter.printBarcode(barcodeData, Printer.BarcodeType.CODE39);
                            //打印完走纸设置的行数
                            mContext.mPrinter.setFeedRow(0, p_distance);
                            break;
                        case 4:
                            mContext.mPrinter.printBarcode(barcodeData, Printer.BarcodeType.ITF_Interleaved_2_of_5);
                            //打印完走纸设置的行数
                            mContext.mPrinter.setFeedRow(0, p_distance);
                            break;
                        case 5:
                            mContext.mPrinter.printBarcode(barcodeData, Printer.BarcodeType.CODE128);
                            //打印完走纸设置的行数
                            mContext.mPrinter.setFeedRow(0, p_distance);
                            break;
                        case 6:
                            //mPrinter.print(barcodeData, Printer.BarcodeType.QR_CODE);
                            Log.d(TAG, "Printer.BarcodeType.QR_CODE====" + barcodeData);
                            try {
                                Bitmap bitmap = CodeUtils.generateBitmap(barcodeData, 320, 320);
                                for (int i = 0; i <= 2; i++) {
                                    mContext.mPrinter.printImage(bitmap);
                                }
                                mContext.mPrinter.setFeedRow(0, p_distance);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                    }

                } catch (Exception var8) {
                    ;
                }
            }
        });
    }

    /**
     * EAN8校验逻辑
     *
     * @param barcodeData 输入的数据
     * @return
     */
    private boolean isValidEAN8(String barcodeData) {
        if (barcodeData.length() != 8) {
            return false;
        }

        int sum = 0;
        for (int i = 0; i < 7; i += 2) {
            sum += Character.getNumericValue(barcodeData.charAt(i));
        }
        for (int i = 1; i < 8; i += 2) {
            sum += 3 * Character.getNumericValue(barcodeData.charAt(i));
        }

        return (sum % 10 == 0);
    }

    /**
     * EAN13校验逻辑
     *
     * @param barcodeData
     * @return
     */
    private boolean isValidEAN13(String barcodeData) {
        if (barcodeData.length() != 13) {
            return false;
        }

        int sum = 0;
        for (int i = 0; i < 12; i++) {
            int digit = Character.getNumericValue(barcodeData.charAt(i));
            if (i % 2 == 0) {
                sum += digit;
            } else {
                sum += 3 * digit;
            }
        }

        int checksum = (10 - (sum % 10)) % 10;
        int lastDigit = Character.getNumericValue(barcodeData.charAt(12));

        return (checksum == lastDigit);
    }

    /**
     * 获取包裹在LinearLayout里面的radioGroupid的方法
     *
     * @param radioGroup
     * @return
     */
    private int getCheckedRadioButtonIdInRadioGroup(RadioGroup radioGroup) {
        int checkedRadioButtonId = -1;
        int childCount = radioGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = radioGroup.getChildAt(i);
            if (view instanceof LinearLayout) {
                LinearLayout linearLayout = (LinearLayout) view;
                int radioButtonCount = linearLayout.getChildCount();
                for (int j = 0; j < radioButtonCount; j++) {
                    View radioButton = linearLayout.getChildAt(j);
                    if (radioButton instanceof RadioButton) {
                        if (((RadioButton) radioButton).isChecked()) {
                            checkedRadioButtonId = radioButton.getId();
                            break;
                        }
                    }
                }
            }
        }
        return checkedRadioButtonId;
    }

    /**
     * 单选框按钮被选中时候的条码展示区以及提示信息
     * img_code.setImageBitmap(CodeUtils.create****Barcode(******)),这个是点击选中按钮后生成的预览条码
     */
    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.code_upc:
                    if (isChecked) {
                        code_ean8.setChecked(false);
                        code_ean13.setChecked(false);
                        code_code39.setChecked(false);
                        code_itf.setChecked(false);
                        code_code128.setChecked(false);
                        code_qr.setChecked(false);
                        previewtext.setText("预览：UPC-A");
                        texthint.setText("字符数：11，范围:0~9,自动校验");
                        et_hint.setText("12345678911");
                        img_code.setImageBitmap(CodeUtils.createUPCABarcode("12345678911"));
                        break;
                    }
                case R.id.code_ean8:
                    if (isChecked) {
                        code_upc.setChecked(false);
                        code_ean13.setChecked(false);
                        code_code39.setChecked(false);
                        code_itf.setChecked(false);
                        code_code128.setChecked(false);
                        code_qr.setChecked(false);
                        previewtext.setText("预览：EVAN8");
                        texthint.setText("字符数：7，范围:0~9,自动校验");
                        et_hint.setText("1234567");
                        img_code.setImageBitmap(CodeUtils.createEAN8Barcode("1234567"));
                        break;
                    }
                case R.id.code_ean13:
                    if (isChecked) {
                        code_upc.setChecked(false);
                        code_ean8.setChecked(false);
                        code_code39.setChecked(false);
                        code_itf.setChecked(false);
                        code_code128.setChecked(false);
                        code_qr.setChecked(false);
                        previewtext.setText("预览：EVN13");
                        texthint.setText("字符数：12，范围:0~9,自动校验");
                        et_hint.setText("165874239824");
                        img_code.setImageBitmap(CodeUtils.createEAN13arcode("165874239824"));
                        break;
                    }
                case R.id.code_code39:
                    if (isChecked) {
                        code_upc.setChecked(false);
                        code_ean13.setChecked(false);
                        code_ean8.setChecked(false);
                        code_itf.setChecked(false);
                        code_code128.setChecked(false);
                        code_qr.setChecked(false);
                        previewtext.setText("预览：CODE39");
                        texthint.setText("字符数：1~24，范围:0~9、A~Z、空、$、%、+、-、。、/");
                        et_hint.setText("123456789");
                        img_code.setImageBitmap(CodeUtils.createCODE39arcode("123456789"));
                        break;
                    }
                case R.id.code_itf:
                    if (isChecked) {
                        code_upc.setChecked(false);
                        code_ean13.setChecked(false);
                        code_code39.setChecked(false);
                        code_ean8.setChecked(false);
                        code_code128.setChecked(false);
                        code_qr.setChecked(false);
                        previewtext.setText("预览：ITF");
                        texthint.setText("字符数：≤24(偶数)，范围:0~9");
                        et_hint.setText("1234567891");
                        img_code.setImageBitmap(CodeUtils.createITFarcode("1234567891"));
                        break;
                    }
                case R.id.code_code128:
                    if (isChecked) {
                        code_upc.setChecked(false);
                        code_ean13.setChecked(false);
                        code_code39.setChecked(false);
                        code_itf.setChecked(false);
                        code_ean8.setChecked(false);
                        code_qr.setChecked(false);
                        previewtext.setText("预览：CODE128");
                        texthint.setText("字符数：1~30，范围:任意字符,不包括汉字");
                        et_hint.setText("123456789ABC");
                        img_code.setImageBitmap(CodeUtils.createCODE128Barcode("123456789ABC"));
                        break;
                    }
                case R.id.code_qr:
                    if (isChecked) {
                        code_upc.setChecked(false);
                        code_ean13.setChecked(false);
                        code_code39.setChecked(false);
                        code_itf.setChecked(false);
                        code_code128.setChecked(false);
                        code_ean8.setChecked(false);
                        previewtext.setText("预览：QR");
                        texthint.setText("范围：任意字符");
                        et_hint.setText("abcdefg1234567890ABCDEFG");
                        img_code.setImageBitmap(CodeUtils.createQrcode("123456789ABC"));
                        break;
                    }
            }
        }
    };
}
